# encoding: UTF-8
# user：admin at 2017/7/5

import hashlib
import web
import receive
import reply

class Handle:
    def GET(self):
        '''
        验证是否为微信服务器发送过来的消息
        :return:echostr
        '''
        try:
            data=web.input()
            if len(data)==0:
                return "hello,this is handle view."

            signature=data.signature
            timpestamp=data.timestamp
            noce=data.once
            echostr=data.echostr
            token="weixin" #请按照公众平台官网\基本配置中信息填写

            list=[token,timpestamp,noce]
            list.sort()
            sha1=hashlib.sha1()
            map(sha1.update,list)
            hashcode=sha1.hexdigest()
            print "handle/GET func:hashcode,signature:",hashcode,signature
            if hashcode==signature:
                return echostr
            else:
                return ""

        except Exception,Argument:
            return Argument

    def POST(self):
        try:
            webData=web.data()
            print "Handle Post webdata is ",webData     #后台打印日志
            recMsg=receive.parse_xml(webData)

            if isinstance(recMsg,receive.Msg) :
                #实现粉丝号发送文本消息来，公众号回复test文本给粉丝号
                toUser=recMsg.FromUserName
                fromUser=recMsg.ToUserName

                if recMsg.MsgType=="text":
                    content="test"
                    replyMsg=reply.TextMsg(toUser,fromUser,content)
                    return replyMsg.send()
                elif recMsg.MsgType=="image":
                    mediaId=recMsg.MediaId
                    replyMsg=reply.ImageMsg(toUser,fromUser,mediaId)
                    return replyMsg.send()
                else:
                    return reply.Msg().send()
            else:
                print "暂且不处理"
                return reply.Msg().send()

        except Exception,Argment:
            return Argment